<template>
  <div id="conentpage" class="rightBodyContent">
    <div class="rightBodyContent-in">
      <el-button type="primary" plain @click="backlist" size="small" v-if="editId"><i class="el-icon-back"></i>返回列表
      </el-button>
      <el-row class="warp">
        <el-col :span="24" class="warp-main">
          <el-form ref="infoForm" :model="infoForm" :rules="rules" label-width="140px">
            <el-form-item label="问卷标题:" prop="title">
              <el-input v-model="infoForm.title" placeholder="填写投票名称"></el-input>
            </el-form-item>
            <el-form-item label="问卷范围:">
              <el-radio-group v-model="teachertype" @change="radiochangeTab">
                <el-radio :label="0">全校职工</el-radio>
                <el-radio :label="1">特定职工</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="选择特定职工:" v-if="teachertype==1">
              <el-button type="primary" @click="chooseStudent" class="mb-10" size="small" plain>选择参与问卷人员</el-button>
              <el-button @click.native="groupVisible=true" size="small">选择执行群组（多选）</el-button>
              <div>
                <el-tag
                    :key="tag.id"
                    v-for="(tag,index) in dynamicTags"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(index)"
                    class="mr-10"
                >{{tag.realname}}
                </el-tag>
              </div>
            </el-form-item>
            <el-form-item label="问卷开始时间:" prop="end_time">
              <el-col :span="11">
                <el-date-picker type="date"
                                placeholder="开始时间"
                                v-model="infoForm.start_time"
                                :picker-options="pickerOptions1"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="问卷结束时间:" prop="end_time">
              <el-col :span="11">
                <el-date-picker type="date"
                                placeholder="结束时间"
                                v-model="infoForm.end_time"
                                :picker-options="pickerOptions1"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="问卷内容:">
              <div class="iconlist questionlist" v-for="(item,i) in infoForm.body">
                <div>{{i+1}}.
                  <el-input v-model="infoForm.body[i].content" placeholder="填写问卷内容"></el-input>
                  <i class="el-icon-circle-plus-outline iconadd addicon" @click="onAdd(i)" v-if="i==0"></i>
                  <i class="el-icon-error iconadd detelicon" @click="onDetel(i)" v-else></i>
                </div>
                <div>
                  用户问卷回答类型：
                  <el-radio-group v-model="infoForm.body[i].type" @change="radioChange(i)">
                    <el-radio label="1">单选项</el-radio>
                    <el-radio label="2">多选项</el-radio>
                    <el-radio label="3">输入框</el-radio>
                  </el-radio-group>
                  <span class="infoline">(选项：用户选择ABCD选项；输入框：用户自行输入文字内容)</span>
                </div>
                <!--                  1单 2 多 3输入-->
                <div class="questionline" v-if="infoForm.body[i].type==1||infoForm.body[i].type==2">
                  <div v-for="(item,indexs) in infoForm.body[i].option" class="questionline-list">
                    <p>
                      {{qustionCheck[indexs]}}.
                      <el-input v-model="infoForm.body[i].option[indexs].text" placeholder="填写选项内容"></el-input>
                      <span v-if="indexs==0">
                          <i class="el-icon-circle-plus-outline iconadd addicon" @click="addlinebox(i)"
                             v-if="infoForm.body[i].option.length<7"></i>
                          </span>
                      <i class="el-icon-error iconadd detelicon" @click="detellinebox(i,indexs)" v-else></i>
                    </p>
                    <p>
                      是否添加输入框：
                      <el-radio-group v-model="infoForm.body[i].option[indexs].type">
                        <el-radio label="1">是</el-radio>
                        <el-radio label="2">否</el-radio>
                      </el-radio-group>
                    </p>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit" size="small">确认提交</el-button>
              <el-button @click="backlist" size="small">返回</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <teacherMultiple :visible.sync="studentVisible" @studentFn="studentFn" :userclassId="infoForm.class_id"
                     :usersectionId="infoForm.section_id" :dynamicTagsArray="dynamicTagsArray"></teacherMultiple>
    <!--    选择群组-->
    <groupModule :visible.sync="groupVisible" @studentFn="studentFn"></groupModule>
  </div>
</template>

<script>
import {yeartime} from '@/assets/js/common'
import classInput from '@/components/template/classInput.vue'
import sectionInput from '@/components/template/sectionInput.vue'
import teacherMultiple from '@/components/dialog/teacherMultiple.vue'
import {pagination} from '@/utils/util.js'

export default {
  components: {
    classInput,
    sectionInput,
    teacherMultiple
  },
  data () {
    return {
      groupVisible: false,
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      qustionCheck: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      dialogTableVisible: false,
      infoForm: {
        body: [{'content': null, 'type': '1', 'option': [{text: '', type: '2'}]}],
        title: '',
        start_time: yeartime(new Date()),
        end_time: yeartime(new Date()),
        user_ids: 0
      },
      // 表单验证
      rules: {
        title: [
          {required: true, message: '填写问卷标题', trigger: 'blur'}
        ]
      },
      pickerOptions1: {
        disabledDate (time) {
          return time.getTime() < Date.now() // - 8.64e7
        }
      },
      arryList: null,
      usersName: null,
      editId: this.$route.query.editId,
      listCheck: [],
      value1: [],
      sectionList: [],
      classesList: [],
      oldClass: {}, // 未处理的班级
      oldsection: {}, // 未处理的年段
      editClass_id: [],
      editsection_id: [],
      studentVisible: false,
      teachertype: 0,
      dynamicTags: [],
      dynamicTagsId: [],
      dynamicTagsArray: {},
      editBody: null
    }
  },
  watch: {
    '$route' (to, from) {
      // 这样就可以获取到变化的参数了，然后执行参数变化后相应的逻辑就行了
      console.log('路由参数变化', this.$route.query, this.$route.query.editId, !this.$route.query.editId)
      if (!this.$route.query.editId) {
        this.editId = ''
      }
    }
  },
  created () {

  },
  mounted () {
    this.Inint()
  },
  methods: {
    Inint () {
      this.$fetch(this.api.questionnaire_inside_detail, {id: this.editId}).then((response) => {
        if (response.code === 0) {
          this.infoForm.start_time = response.vo.start_time
          this.infoForm.end_time = response.vo.end_time
          this.infoForm.title = response.vo.title
          this.listCheck = response.list
          this.infoForm.type = response.vo.type
          this.infoForm.class_id = response.vo.class_id
          // 0全校 1特定年段 2特定班级
          if (Number(response.vo.type) === 1) {
            this.editsection_id = response.vo.section_id
          } else if (Number(response.vo.type) === 2) {
            this.editClass_id = response.vo.class_id
          }
          this.editBody = response.vo
          this.infoForm.body = response.list
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    onEditorReady (editor) {
    },
    onAdd (index) {
      // this.infoForm.body.push({'content': null, 'type': '1', 'option': [{text: '', type: '2'}]})
      this.infoForm.body.splice(index+1, 0, {'content': null, 'type': '1', 'option': [{text: '', type: '2'}]})
    },
    addlinebox (i) {
      this.infoForm.body[i].option.push({text: '', type: '2'})
    },
    detellinebox (i, index) {
      this.infoForm.body[i].option.splice(index, 1)
    },
    onDetel (index) {
      this.infoForm.body.splice(index, 1)
    },
    // 设置默认选中
    checked () {
      for (let i = 0; i < this.arryList.length; i++) {
        if (this.applyBookBox[this.arryList[i].id]) {
          console.log('数值', i)
          this.$refs.table.toggleRowSelection(this.arryList[i], true)
        }
      }
    },
    radioChange (e) {
      if (this.infoForm.body[e].type == 3) {
        this.infoForm.body[e].option = []
      } else {
        this.infoForm.body[e].option = [{text: '', type: '2'}]
      }
    },
    backlist () {
      this.$router.go(-1)
    },
    radiochangeTab () {
      this.infoForm.user_ids = 0
    },
    onSubmit () {
      // 提交 this.$refs.infoForm.validate，这是表单验证
      if (!this.infoForm.title) {
        this.$message({
          message: '请填写问卷标题',
          type: 'error'
        })
        return
      }
      // 1单 2 多 3输入
      for (let i in this.infoForm.body) {
        if (!this.infoForm.body[i].content) {
          this.$message({
            message: '请填写问卷内容',
            type: 'error'
          })
          return
        }
        if (this.infoForm.body[i].type == 1 || this.infoForm.body[i].type == 2) {
          for (let j in this.infoForm.body[i].option) {
            if (!this.infoForm.body[i].option[j].text) {
              console.log('none')
              this.$message({
                message: '请填写问卷选项',
                type: 'error'
              })
              return
            }
          }
        }
      }
      if (this.teachertype === 1 && !this.dynamicTags.length) {
        this.$message({
          message: '请选择特定职工',
          type: 'error'
        })
        return
      }
      let data_ = {}
      let body_ = this.infoForm.body
      for (let i in body_) {
        if (body_[i].type !== 3) {
          for (let j in body_[i].option) {
            body_[i].option[j]['index'] = this.qustionCheck[j]
          }
        }
      }
      let users = []
      for (let item of this.dynamicTags) {
        users.push(item.id)
      }
      data_.title = this.infoForm.title
      data_.start_time = this.infoForm.start_time
      data_.end_time = this.infoForm.end_time
      data_.body = JSON.stringify(body_)
      data_.user_ids = users.join(',')
      this.$refs['infoForm'].validate((valid) => {
        if (valid) {
          this.$post(this.api.questionnaire_inside_add, data_).then(res => {
            if (res.code === 0) {
              this.$message({
                message: '复制成功',
                type: 'success'
              })
              this.backlist()
              this.infoForm = {
                body: [{'title': null, 'type': '1', 'content': ['']}],
                title: '',
                class_id: '',
                section_id: '',
                start_time: yeartime(new Date()),
                end_time: yeartime(new Date()),
                student_id: 0
              }
              this.teachertype = 0
              this.dynamicTags = []
              this.dynamicTagsId = []
              this.dynamicTagsArray = {}
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          })
        }
      })
    },
    chooseStudent () {
      let list = {}
      for (let item of this.dynamicTags) {
        list[item.id] = item
      }
      this.dynamicTagsArray = this.getJson(list)
      this.studentVisible = true
    },
    handleClose (index) {
      this.dynamicTags.splice(index, 1)
    },
    studentFn (option) {
      let list = [];
      for (let i in option) {
        list.push(option[i])
      }
      this.dynamicTags = this.getJson(list)
    },
    getJson(option){
      return JSON.parse(JSON.stringify(option))
    },
  }
}
</script>
<style lang="scss">


.questionlist:last-child .questionlist {
  border-bottom: 0;
}

.inlinebox {
  padding-left: 20px;
}

.infoline {
  font-size: 12px;
  color: #777;
  margin-left: 10px;
}

.ql-editor {
  max-height: 250px;
}

.el-dialog__body {
  padding: 0 20px;
}

.el-radio__label {
  /*display: none;*/
}

.warp {
  width: 80%;
  padding: 30px;
  margin: 0 auto;
}

.el-dialog__body {
  /*text-align: center;*/
}

.el-pagination {
  padding-top: 20px;
}


.iconadd {
  cursor: pointer;
  font-size: 20px;
  margin-left: 10px;
}

.iconlist {
  margin-bottom: 10px;
}

.addicon {

}

.detelicon {
  color: red;
}
</style>
